package com.jinsilu.freight.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.exception.ResultException;
import com.hjq.http.listener.HttpCallback;
import com.jinsilu.freight.R;
import com.jinsilu.freight.common.MyActivity;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.helper.ReplaceHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.model.HttpListData;
import com.jinsilu.freight.http.request.BackCardDefaultApi;
import com.jinsilu.freight.http.request.GetIdCardApi;
import com.jinsilu.freight.http.request.GetPublicOrderListApi;
import com.jinsilu.freight.http.request.GetPublicOrderListByIdApi;
import com.jinsilu.freight.http.request.GetVehicleListApi;
import com.jinsilu.freight.http.request.TakeOrderApi;
import com.jinsilu.freight.http.response.BankInfoBean;
import com.jinsilu.freight.http.response.ContractBean;
import com.jinsilu.freight.http.response.IdCardBean;
import com.jinsilu.freight.http.response.SourceHallBean;
import com.jinsilu.freight.http.response.VehicleListBean;
import com.jinsilu.freight.ui.adapter.SourceHallAdapter;
import com.jinsilu.freight.ui.dialog.AddressDialog;
import com.jinsilu.freight.ui.dialog.MessageDialog;
import com.jinsilu.freight.ui.dialog.WebViewDialog;
import com.jinsilu.freight.ui.fragment.SourceHallFragment;
import com.jinsilu.freight.ui.fragment.UnfinishedWaybillFragment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 扫码订单列表
 *
 * @author yangyang
 * @time 2021/03/02 16:06
 */
public class ScanOrderListActivity extends MyActivity {

    private SmartRefreshLayout refresh;
    private RecyclerView recycler;
    private SourceHallAdapter mAdapter;

    private Integer mCurrentPage = 1;

    private String mPartnerId;

    public static SourceHallFragment newInstance() {
        return new SourceHallFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scan_order_list;
    }

    @Override
    protected void initView() {

        recycler = findViewById(R.id.recycler);
        refresh = findViewById(R.id.refresh);

        refresh.setEnableLoadMore(false);

        recycler.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerDecoration.builder(this)
                .asSpace().size(10, TypedValue.COMPLEX_UNIT_DIP)
                .showSideDividers()
                .showFirstDivider()
                .showLastDivider()
                .build()
                .addTo(recycler);

        mAdapter = new SourceHallAdapter(new ArrayList<>());

        recycler.setAdapter(mAdapter);

        mAdapter.addChildClickViewIds(R.id.item_view_details);
        mAdapter.addChildClickViewIds(R.id.item_take_order);
        mAdapter.addChildClickViewIds(R.id.send_phone);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            SourceHallBean sourceHallBean = (SourceHallBean) adapter.getData().get(position);
            if (view.getId() == R.id.item_take_order) {
                if (!CommonHelper.isLogin()) {
                    CommonHelper.goLoin();
                    return;
                }
                if (1 != CommonHelper.getCertificationStatus()) {
                    toast("认证后方可操作");
                    return;
                }
                checkBackCard(sourceHallBean);
            } else if (view.getId() == R.id.item_view_details) {
                Intent intent = new Intent(this, SourceMallDetailsActivity.class);
                intent.putExtra("toNumber", sourceHallBean.getOrderNumber());
                startActivity(intent);
            } else if (view.getId() == R.id.send_phone) {
                if (!TextUtils.isEmpty(sourceHallBean.getConsignorPhone())) {
                    PhoneUtils.dial(sourceHallBean.getConsignorPhone());
                }
            }
        });

        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mCurrentPage += 1;
                getPublicOrderList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mCurrentPage = 1;
                getPublicOrderList();
            }
        });
    }


    private void checkBackCard(SourceHallBean sourceHallBean) {

        // 查询银行卡信息
        EasyHttp.get(this)
                .api(new BackCardDefaultApi())
                .request(new HttpCallback<HttpData<BankInfoBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<BankInfoBean> data) {
                        checkBackCardInfo(data.getData(),sourceHallBean);
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        if (e instanceof ResultException) {
                            new MessageDialog.Builder(getContext())
                                    // 标题可以不用填写
                                    .setTitle("提示")
                                    // 内容必须要填写
                                    .setMessage("暂无默认银行卡,请先绑定银行卡后再继续操作！")
                                    // 确定按钮文本
                                    .setConfirm("绑卡")
                                    // 设置 null 表示不显示取消按钮
                                    .setCancel("继续")
                                    // 设置点击按钮后不关闭对话框
                                    //.setAutoDismiss(false)
                                    .setListener(new MessageDialog.OnListener() {

                                        @Override
                                        public void onConfirm(BaseDialog dialog) {
                                            startActivity(MyBankManageActivity.class);
                                        }

                                        @Override
                                        public void onCancel(BaseDialog dialog) {
                                            takeOrders(sourceHallBean,"0");
                                        }
                                    })
                                    .show();
                        }
                    }

                });
    }

    private void checkBackCardInfo(BankInfoBean bankInfoBean,SourceHallBean sourceHallBean){
        if(
                TextUtils.isEmpty(bankInfoBean.getAccountHolderPhone()) ||
                        TextUtils.isEmpty(bankInfoBean.getIdentityCardFrontImg()) ||
                        TextUtils.isEmpty(bankInfoBean.getIdentityCardReverseImg())
        ){
            new MessageDialog.Builder(getContext())
                    // 标题可以不用填写
                    .setTitle("提示")
                    // 内容必须要填写
                    .setMessage("银行卡信息缺少，请补充缺失信息！")
                    // 确定按钮文本
                    .setConfirm("补充信息")
                    // 设置 null 表示不显示取消按钮
                    //.setAutoDismiss(false)
                    .setListener(new MessageDialog.OnListener() {

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            Intent intent = new Intent(getContext(), MyBankEditActivity.class);
                            intent.putExtra("bankInfo",bankInfoBean);
                            startActivity(intent);
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {

                        }
                    })
                    .show();
        }else {
            showBackCardConfirmDialog(bankInfoBean,sourceHallBean);
        }

    }

    private void showBackCardConfirmDialog(BankInfoBean bankInfoBean,SourceHallBean sourceHallBean){
        // 自定义对话框®
        BaseDialog baseDialog = new BaseDialog.Builder(this)
                .setContentView(R.layout.dialog_default_bank_confirm)
                .setAnimStyle(BaseDialog.ANIM_SCALE)
                .show();

        ((TextView)baseDialog.findViewById(R.id.tv_bank_name)).setText(bankInfoBean.getBankName());
        ((TextView)baseDialog.findViewById(R.id.et_user_name)).setText(bankInfoBean.getAccountHolder());
        ((TextView)baseDialog.findViewById(R.id.et_id_card_number)).setText(ReplaceHelper.iDCardFormat(bankInfoBean.getIdentityCard()));
        ((TextView)baseDialog.findViewById(R.id.et_bank_card_number)).setText(ReplaceHelper.bankCardFormat(bankInfoBean.getBankCard()));


        baseDialog.findViewById(R.id.btn_submit_one).setOnClickListener(view -> {
            startActivity(MyBankManageActivity.class);
            baseDialog.dismiss();
        });

        baseDialog.findViewById(R.id.btn_submit_two).setOnClickListener(view -> {
            takeOrders(sourceHallBean,"1");;
            baseDialog.dismiss();
        });


    }


    @Override
    protected void initData() {
        mPartnerId = getIntent().getStringExtra("toNumber");
        getPublicOrderList();
    }

    private void takeOrders(SourceHallBean sourceHallBean,String confirmBank) {
        // 检查运价是否为0
        if (sourceHallBean != null && sourceHallBean.getSettlePrice() > 1) {
            getIdCardStatus(confirmBank,sourceHallBean);
            return;
        }
        executeTakeOrder(sourceHallBean.getOrderNumber(),confirmBank);
    }

    /**
     * 获取身份验证状态
     */
    private void getIdCardStatus(String confirmBank, SourceHallBean sourceHallBean) {
        EasyHttp.get(this)
                .api(new GetIdCardApi())
                .request(new HttpCallback<HttpData<IdCardBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<IdCardBean> data) {
                        getVehicleList(confirmBank,data.getData(),sourceHallBean);
                    }
                });
    }



    private void getVehicleList(String confirmBank, IdCardBean idCardBean, SourceHallBean sourceHallBean) {
        // 车辆列表
        EasyHttp.get(this)
                .api(new GetVehicleListApi().setPageNum(String.valueOf(1)).setPageSize("1"))
                .request(new HttpCallback<HttpData<VehicleListBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<VehicleListBean> data) {
                        List<VehicleListBean> vehicleListBeans = data.getRows();
                        showAgreeDialog(confirmBank,idCardBean,vehicleListBeans.get(0),sourceHallBean);
                    }
                });
    }

    private void showAgreeDialog(String confirmBank, IdCardBean idCardBean , VehicleListBean vehicleListBean, SourceHallBean sourceHallBean){
        try {


            new WebViewDialog.Builder(getContext())
                    .setTitle("协议签署")
                    .setHtmlContent(getContext(),sourceHallBean,idCardBean,vehicleListBean)
                    .setListener(new WebViewDialog.OnListener() {
                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            executeTakeOrder(sourceHallBean.getOrderNumber(), confirmBank);
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            // 用户取消，不做任何操作
                        }
                    })
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void executeTakeOrder(String toNumber, String confirmBank) {
        // 接单
        EasyHttp.post(this)
                .api(new TakeOrderApi()
                        .setOrderNumber(toNumber)
                        .setConfirmBank(confirmBank)
                )
                .request(new HttpCallback<HttpData<ContractBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<ContractBean> data) {
                        toast(data.getMessage());
//                        mAdapter.remove(sourceHallBean);
                        BusUtils.postSticky(UnfinishedWaybillFragment.TAG_NEED_TO_REFRESH_WAYBILL); // UnfinishedWaybillFragment will receive
                    }

                    @Override
                    public void onFail(Exception e) {
                        if (e instanceof ResultException) {
                            ResultException resultException = (ResultException) e;
                            HttpData<String> httpData = resultException.getData();
                            if (303 == httpData.getCode()) {
                                BrowserActivity.start(getActivity(), httpData.getMessage());
                            } else {
                                toast(httpData.getMessage());
                            }
                        }
                    }
                });
    }

    private void getPublicOrderList() {
        // 获取货源列表
        EasyHttp.get(this)
                .api(new GetPublicOrderListByIdApi().setPageNum(String.valueOf(mCurrentPage)).setPageSize("10")
                        .setPartnerId(mPartnerId))
                .request(new HttpCallback<HttpListData<SourceHallBean>>(this) {
                    @Override
                    public void onSucceed(HttpListData<SourceHallBean> data) {
                        CommonHelper.finishedLoading(refresh);
                        List<SourceHallBean> sourceHallBeans = data.getData();
                        if (sourceHallBeans.isEmpty()) {
                            mAdapter.setEmptyView(R.layout.layout_empty_order_view);
                            refresh.setEnableLoadMore(false);
                            return;
                        }

                        refresh.setEnableLoadMore(sourceHallBeans.size() >= 10);

                        if (mCurrentPage == 1)
                            mAdapter.setList(sourceHallBeans);
                        else
                            mAdapter.addData(sourceHallBeans);
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        CommonHelper.finishedLoading(refresh);
                        if (e instanceof ResultException) {
                            if (e.getMessage().equals("暂无数据")) {
                                mAdapter.setEmptyView(R.layout.layout_empty_order_view);
                                refresh.setEnableLoadMore(false);
                            }
                        }
                    }
                });
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }
}
